<template>
  <div class="container">
    <header>
      <!-- 标签栏 -->
      <van-tabs 
        v-model="activeName"
        class="tabs" 
        @click="onTabClick"
      >
        <van-tab 
          v-for="channel in channelList"
          :key="channel.id"
          :name="channel.id"
          :title="channel.name"
        />
      </van-tabs>
      <!-- 头部右侧功能区 -->
      <div class="features">
        <!-- 搜索 -->
        <van-icon class="feature" size="20px" name="search" @click="goSearch" />
        <!-- 编辑频道 -->
        <van-icon class="feature" size="20px" name="ellipsis" @click="openPopup" />
      </div>
    </header>
    <van-loading v-if="loading" vertical class="loading" />
    <section v-else>
      <!-- 内容区域 -->
      <news-item
        v-for="news in newsList"
        :key="news.art_id"
        :title="news.title"
        :author="news.aut_name"
        :commentCount="news.comm_count"
        :timestamp="news.pubdate"
        :images="news.cover.images"
        :newsId="news.art_id"
      />
    </section>
    <van-popup 
      v-model="popupVisible" 
      closeable
      position="left"
    >
      <div class="popup">
        <!-- 我的频道 -->
        <div class="title">
          我的频道:
          <span class="sub-title">点击进入频道</span>
          <van-button 
            plain 
            round
            size="mini"
            color="orange"
            class="btn"
            @click="onChannelEdit"
          >
            {{ editing ? '完成' : '编辑' }}
          </van-button>
        </div>
        <div 
          v-for="channel in channelList"
          :key="channel.id"
          :class="{
            tag: true,
            active: activeName === channel.id,
          }"
          @click="goNewsList(channel.id)"
        >
          {{ channel.name }}
          <div 
            v-if="editing" 
            class="remove-btn"
            @click="onRemoveChannel(channel.id)"
          >
            <van-icon name="cross" />
          </div>
        </div>
        <!-- 可选频道 -->
        <div class="title">可选频道:</div>
        <div 
          v-for="channel in selectableChannelList"
          :key="channel.id"
          class="tag"
          @click="onAddChannel(channel.id)"
        >
          + {{ channel.name }}
        </div>
      </div>
      <van-overlay :show="channelLoading">
        <div class="loading-wrapper">
          <van-loading type="spinner" color="#1989fa" />
        </div>
      </van-overlay>
    </van-popup>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import * as api from '@/api/homepage';

export default {
  data () {
    return {
      // 页面状态
      loading: false,
      // 当前tab选中的频道id
      activeName: 0,
      // 是否显示弹出层
      popupVisible: false,
      // 是否正在编辑
      editing: false,
      // 频道操作的loading
      channelLoading: false,
    };
  },
  computed: {
    ...mapState('homepage', [
      'channelList', // { id: 1, name: '推荐' }[]
      'allChannelList', 
      'newsList',
    ]),
    // 可选频道
    selectableChannelList () {
      return this.allChannelList.filter(channel => !this.channelList.some(c => c.id === channel.id));
    },
  },
  methods: {
    ...mapActions('homepage', [
      'updateChannelList', 
      'updateAllChannelList', 
      'updateNewsList',
    ]),
    // 点击频道跳转
    goNewsList (id) {
      this.popupVisible = false;
      this.$router.push({ 
        path: '/', 
        query: {
          id,
        },
      });
      this.activeName = id;
      this.onTabClick(id);
    },
    // 按照新频道列表更新
    async updateUserChannelList (newChannelList) {
      // 开启loading
      this.channelLoading = true;
      const res = await api.setChannelList(newChannelList);
      // 刷新用户频道列表
      await this.updateChannelList();
      // 关闭loading
      this.channelLoading = false;
      // 提示
      this.$notify({ 
        type: 'success',
        message: res.data.message,
      });
    },
    // 删除频道
    async onRemoveChannel (id) {
      const newChannelList = this.channelList.filter(item => item.id !== id);
      this.updateUserChannelList(newChannelList);
    },
    // 添加频道
    async onAddChannel (id) {
      // this.channelList  { id: string, name: string }[]
      // 1. 在this.channelList基础上加一项
      // 2. 把新的channelList 变成{ id: string, seq: string }[]
      const newChannelList = this.channelList.concat({ id }).map((item, i) => ({ id: item.id, seq: i }));
      this.updateUserChannelList(newChannelList);
    },
    // 修改编辑状态
    onChannelEdit () {
      this.editing = !this.editing;
    },
    // vant tab click事件: 回调参数: name：标识符，title：标题
    async onTabClick (id) {
      this.loading = true;
      // 1. 请求新闻列表
      await this.updateNewsList(id);
      this.loading = false;
      // 2. 改路由的query
      this.$router.push({ 
        path: '/',
        query: {
          id,
        },
      });
    },
    // 跳转搜索页面
    goSearch () {
      this.$router.push('/search');
    },
    // 打开弹出层
    openPopup () {
      this.popupVisible = true;
      // 获取全部频道列表
      this.updateAllChannelList();
    },
  },
  async created () {
    // 请求频道列表
    await this.updateChannelList();

    // 页面开始时 应该按照路由中的id高亮tab项 并且请求新闻列表
    // 1. 按照路由高亮tabs的tab项
    this.activeName = this.$route.query.id !== undefined 
      // 1.1 路径有id的时候 直接用
      ? Number(this.$route.query.id) 
      // 1.2 路径没有id的时候 拿频道列表第一项的id
      : this.channelList[0].id;

    // 2. 按照id请求新闻列表
    this.onTabClick(this.activeName);
  },
}
</script>

<style lang="less" scoped>
.loading-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
.popup {
  height: 100vh;
  width: 100vw;
  background-color: #fff;
  padding: 50px 0 0 16px;
  box-sizing: border-box;

  .title {
    display: flex;
    width: 100%;
    align-items: center;
    margin-bottom: 16px;
    
    .sub-title {
      flex: 1;
      color: #ccc;
      font-size: 12px;
      margin-left: 16px;
    }

    .btn {
      padding: 0 16px;
      margin-right: 16px;
    }
  }

  .tag {
    font-size: 14px;
    padding: 8px 16px;
    border-radius: 999px;
    background: #f5f5f5;
    display: inline-block;
    margin: 0 16px 16px 0;
    position: relative;

    &.active {
      color: orange;
    }

    // 编辑中 移除按钮
    .remove-btn {
      padding: 2px;
      background: #aaa;
      color: #fff;
      font-size: 12px;
      position: absolute;
      top: -6px;
      right: -4px;
      border-radius: 50%;
    }
  }
}
.loading {
  margin-top: 24px;
}
.container {
  height: 100%;
  display: flex;
  flex-direction: column;

  header { 
    width: 100vw;
    display: flex;
    align-items: center;
    height: 44px;
    box-shadow: 0 2px 3px #eee;

    .tabs {
      flex: 1;
      height: 44px;
      overflow: hidden;
    }

    .features {
      box-shadow: -30px 0 10px rgb(255, 255, 255, .6);
      overflow-y: hidden;
      height: 100%;
      display: flex;
      align-items: center;
      position: relative;

      .feature {
        width: 20px;
        display: block;
        padding: 0 8px;
      }
    }
    
  }

  section {
    flex: 1;
    overflow-y: auto;
    width: 100%;
  }

}
</style>